RED='\e[1;31m' # 红
GREEN='\e[1;32m' # 绿
YELLOW='\e[1;33m' # 黄
BLUE='\e[1;34m' # 蓝
PINK='\e[1;35m' # 粉红
RES='\e[0m' # 清除颜色
k=""
##字体颜色
jcapt(){
if ps -e | grep -q "apt"; then
  # 如果有，杀死相关进程
  echo -e "$(gettime)${RED}有其他apt程序正在运行,正在杀死相关进程${RES}"
  aptjc=$(pgrep -x apt)
  aptgetjc=$(pgrep -x apt-get)
   for i in ${aptjc}
   do
   kill -9 ${i}
   done
   for i in ${aptgetjc}
   do
   kill -9 ${i}
   done
  echo -e "$(gettime)${GREEN}清理成功\n 正在尝试修复dpkg${RES}"
  zxpd dpkg --configure -a
  apt --fix-broken install
else
  zxpd dpkg --configure -a
  apt --fix-broken install
fi
}
laststart(){
        
        plugin_list(){ 
        ls ${HOME}/gancm/server/
        }
        plugins_number=$(plugin_list)
        list=0
        newplugins_list=$(
            for i in $plugins_number ; do
                let list++
                        for plugins_name in $list ; do
                            oldplugins_list=""$i" "$plugins_name" "
                            echo $oldplugins_list
                        done
            done
            )
                let list++
                while true; do
                server_v=$(whiptail --title "选择种类" --menu "管理shell面板" 20 50 6 \
                    $newplugins_list 返回上级 0 3>&1 1>&2 2>&3)
            case ${server_v} in
            返回上级)
            break
            ;;
            *)
            killo=$(echo $?)
            if [ $killo !=  0 ] ;then
            break
            fi
            laststart_b
            esac
            done
}
laststart_b(){
        plugin_list_b(){ 
        ls ${HOME}/gancm/server/${server_v}
        }
        plugins_number_b=$(plugin_list_b)
        list=0
        newplugins_list_b=$(
            for j in $plugins_number_b ; do
                let list++
                        for plugins_name_b in $list ; do
                            oldplugins_list_b=""$j" "$plugins_name_b" "
                            echo $oldplugins_list_b
                        done
            done
            )
                let list++
                while true; do
                server_number=$(whiptail --title "选择版本" --menu "管理shell面板" 20 50 6 \
                    $newplugins_list_b 返回上级 0 3>&1 1>&2 2>&3)
            case ${server_number} in
            返回上级)
            break
            ;;
            *)
            killo=$(echo $?)
            if [ $killo !=  0 ] ;then
            break
            fi
            gljb
            esac
            done
}
starterver(){
            if [ "${server_number}" = "1.20.1" ]; then
                if [ ! -f "$(command -v java)" ];then
                    echo -e "$(gettime)${RED}目前并没有安装 java17 正在安装${RES}"
                    apt install openjdk-17-jdk
                fi
            fi
            if [ ! -f ${HOME}/gancm/server/${server_number}/start.sh ]; then
            big_nc=$(whiptail --title "最大占用内存" --inputbox "Java 程序 -Xmx 参数，必须填写单位，如：1024M，2G 等" 10 60 3G 3>&1 1>&2 2>&3)
                    exitstatus=$?
                        if [ $exitstatus != 0 ]; then
                            echo -e "${gettime}${RED}没有填写进程取消${RES}"
                            hcjx
                            exit 1
                        fi
            smali_nc=$(whiptail --title "最小内存" --inputbox "Java 程序 -Xms 参数，必须填写单位，如：1024M，2G 等 $( ls ${HOME}/gancm/server/)" 10 60 1G 3>&1 1>&2 2>&3)
                    exitstatus=$?
                        if [ $exitstatus != 0 ]; then
                            echo -e "${gettime}${RED}没有填写进程取消${RES}"
                            hcjx
                            exit 1
                        fi
                    echo -e "java -Xmx${big_nc} -Xms${smali_nc} -Dfile.encoding=UTF-8 -Duser.language=zh -Duser.country=CN -jar ${HOME}/gancm/server/${server_v}/${server_number}/server.jar -nogui " > ${HOME}/gancm/server/${server_v}/${server_number}/start.sh 
        fi
        STARTTIME=`date +%s`
        cd ${HOME}/gancm/server/${server_v}/${server_number}/ && echo -e "eula=true" > eula.txt && bash ${HOME}/gancm/server/${server_v}/${server_number}/start.sh
        ENDTIME=`date +%s`
        DELTATIME=`expr $ENDTIME - $STARTTIME`
        if [ "$DELTATIME" -le "20" ]; then
            echo -e "$(gettime)${YELLOW}脚本用时 $DELTATIME sec（s）. ${RES}\n${RED}脚本运行后在短时间内退出 可能是由路径填写错误 或 安装不完整 ${RES}"
        fi
}
download(){
     OPTION=$(whiptail --title "选择功能" --menu "请选择操作" 20 50 6 \
        "1" "spigot核心下载 " \
        "2" "paper核心下载" \
        "0" "返回上级" 3>&1 1>&2 2>&3)
        case $OPTION in
        1)
          download_spigot
          ;;
        2)
          download_paper
          ;;
        0)
          break
          ;;
        *)
          return
          esac
}
gljb(){
while true; do
OPTION=$(whiptail --title "选择功能" --menu "请选择操作" 20 50 6 \
     "1" "启动服务器[${server_number}] " \
     "2" "删除服务器[${server_number}]" \
     "3" "插件商店" \
     "0" "返回上级" 3>&1 1>&2 2>&3)
     case $OPTION in
    1)  
        starterver
        ;;
    2)  
        whiptail --title "删除${server_number}" --yesno "您确定要删除当前服务器吗？此操作不可逆！" 10 60
        # 检查用户的选择
        if [ $? -eq 0 ]; then
             # 用户选择了“是”，执行删除操作
            zxpd rm -rfv ${HOME}/gancm/server/${server_number}
            whiptail --title "操作完成" --msgbox "当前目录已被成功删除！" 10 60
        else
            # 用户选择了“否”或者按下了取消按钮，不执行删除操作
            whiptail --title "操作取消" --msgbox "当前目录未被删除。" 10 60
        fi
     ;;
    3)
        plugin_dow
        ;;
    0)
        return
        ;;
    *)
        break
        esac
        done
}

gettime(){
echo -e "${YELLOW}[$(date +"%Y-%m-%d %H:%M:%S")]${RES} "
}
zxpd() {
    # 创建计数器并初始化为0
    local zxpdml="$@"
    local jsq=0
    local error_file=$(mktemp)

    # 循环执行指令，最多重试3次
    while [ $jsq -lt 4 ]; do
        # 执行指令并隐藏报错信息
        $zxpdml 2>"${error_file}"
        if [ $? -eq 0 ]; then
            # 如果执行成功，则跳出循环
            echo 0 > ${HOME}/log.log
            break
        else
            # 如果执行失败，则重试
            let jsq++
            if [ $jsq -ge 4 ]; then
                # 如果重试次数超过3次，则输出异常信息并跳出循环
                echo 1 > ${HOME}/log.log
                echo -e "$(gettime)${RED}\n指令执行异常${RES}"
                if [ -s "$error_file" ]; then
                    echo -e "$(gettime)${RED}运行日志（请把这一段输出提交给作者）${RES}:"
                    cat "$error_file"
                fi
                rm -rf "$error_file"
                break
            fi
            # 输出重试信息
            echo -e "$(gettime)${RED}指令执行错误，重新执行指令:${YELLOW}${zxpdml}  ${RED}第${YELLOW}${jsq}${RED}次${RES}"
        fi
    done

    # 如果计数器小于0，则输出指令执行错误
    if [ $jsq -lt 0 ]; then
        echo 2 > ${HOME}/log.log
        echo "${RED}指令执行错误${RES}"
    fi
}
jdt(){
pid=$!
    spin='-\|/'
    echo -e "$(gettime)${GREEN}正在下载${YELLOW} ${@} ${GREEN}中 ${RES}\n"
    while kill -0 $pid > /dev/null 2>&1; do
        printf "\b\r${GREEN} ${spin:a++%${#spin}:1} ${RES}"
        sleep 0.1
    done
    while true; do
        while ! kill -0 $pid > /dev/null 2>&1; do
            ret=$(cat ${HOME}/log.log)
            if [ "$ret" = "0" ]; then
                    echo -e "\n$(gettime)下载成功"
                    break 2
            elif [ "$ret" = "1" ]; then
                    echo -e "\n$(gettime)下载失败"
                    break 2
            else
                    echo -e "$(gettime)\n脚本内部运行失败 这是脚本的问题 请反馈给开发者"
                    break 2                 
            fi
            
        done
    done
}


installapt(){
    a=0
    if [ -f "/usr/bin/yum" ] && [ -d "/etc/yum.repos.d" ]; then
            zxpd yum install $@ -y > /dev/null 2>&1 &
            zxpd yum autoremove -y > /dev/null 2>&1 &    	     
	elif [ -f "/usr/bin/apt-get" ] && [ -f "/usr/bin/dpkg" ]; then
	       jcapt
            zxpd apt install $@ -y > /dev/null 2>&1 &
            zxpd apt install $@ -y > /dev/null 2>&1 &
	else
            zxpd pkg install $@ -y > /dev/null 2>&1 &
    fi
    jdt $@
}

hcjx(){
    echo -e "$(gettime)${GREEN}请按回车键继续下一条指令...${RES}"
    read -r
}

fgx(){
    COLS=$(tput cols)
    # 输出#，填满整行
    for ((i=0; i<$COLS; i++)); do
        echo -ne "${YELLOW}#${RES}"
    done
    echo -e "\n"
}
download_all(){
     v_number=$3
            if [ "${v_number}" = "$k" ]; then
                v_number=$(whiptail --title "请输入要下载的版本" --inputbox "例如我想下载 1.20.1 输入 1.20.1即可" 10 60 1.20.1 3>&1 1>&2 2>&3)
                    exitstatus=$?
                        if [ $exitstatus != 0 ]; then
                            echo -e "${gettime}${RED}没有填写进程取消${RES}"
                            hcjx
                            exit 1
                        fi
            fi
            if [ ! -d ${HOME}/gancm/server/${v_name} ];then
               mkdir ${HOME}/gancm/server/${v_name}/
            fi
            if [ ! -d ${HOME}/gancm/server/${v_name}/${v_number} ];then
               mkdir ${HOME}/gancm/server/${v_name}/${v_number}
            fi
     curl -X GET "https://download.fastmirror.net/api/v3/${v_name}/${v_number}?offset=0&limit=5" | jq > ${HOME}/gancm/log/download_${v_name}_list.json
     if [ "$(cat ${HOME}/gancm/log/download_${v_name}_list.json | jq -r '.success')" = "true" ]; then
          download_all_list(){ 
               jq '.data.builds[].core_version' ${HOME}/gancm/log/download_${v_name}_list.json | sed 's/"//g'
          }
          download_all_number=$(download_all_list)
             list=0
             newdownload_all=$(
                 for z in $download_all_number ; do
                     let list++
                             for download_all_name in $list ; do
                                 olddownload_all_list=""${v_number}/${z}" "$list" "
                                 echo $olddownload_all_list
                             done
                 done
                 )
                 echo $newdownload_all
                 download_all_number=$(whiptail --title "选择种类" --menu "管理shell面板" 20 50 6 \
                    $newdownload_all 退出 0 3>&1 1>&2 2>&3)
                    case $download_all_number in
                    退出)
                    return
                    ;;
                    *)
                           killo=$(echo $?)
            if [ $killo !=  0 ] ;then
            return
            fi
                 zxpd wget https://download.fastmirror.net/download/${v_name}/${download_all_number} -O ${HOME}/gancm/server/${v_name}/${v_number}/server.jar &
                 jdt 下载 ${v_name}_${v_number} 特别感谢fastmirror镜像网站 （虽然是我爬的）
                 if [ "${v_number}" != "1.20.1" ]; then
                     echo -e "${gettime}${YEELOW}因为我比较懒（bushi \ 除1.20.1版本请自行安装java环境"
                 fi
                 if [ "${v_number}" = "1.20.1" ]; then
                     if [ ! -f "$(command -v java)" ];then
                         echo -e "$(gettime)${RED}目前并没有安装 java17 正在安装${RES}"
                         apt install openjdk-17 -y
                     fi
                 fi
                 n;
                 esac
          else
               echo -e "$(gettime) ${RED}数据请求失败${RES}"
          fi
}
download_paper(){
     v_name=Paper
     download_all
}
download_spigot(){
            v_name=Spigot
            download_all
}
plugin_dow(){
     case ${server_v} in
               Spigot)
                    case ${server_number} in
                    1.20.1)
                         OPTION=$(whiptail --title "选择功能 ${server_number}_${server_v}" --menu "请选择操作" 20 50 6 \
                         "1" "间歇泉" \
                         "0" "返回上级" 3>&1 1>&2 2>&3)
                                 case ${OPTION} in
                                 1)
                                       if [ ! -d ${HOME}/gancm/server/${server_v}/${server_number}/plugins ]; then
                                       mkdir ${HOME}/gancm/server/${server_v}/${server_number}/plugins
                                       fi
                                       wget https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/spigot -O ${HOME}/gancm/server/${server_v}/${server_number}/plugins/Geyser-Spigot.jar &
                                       jdt 下载适用于Spigot的间歇泉（国外网站下载速度慢）
                                 ;;
                                 esac

                    ;;
                    *)
                         OPTION=$(whiptail --title "选择功能" --menu "请选择操作" 20 50 6 \
                         "0" "返回上级" 3>&1 1>&2 2>&3)
                    ;;
                    esac
               ;;
               Paper)
               case ${server_number} in
                    1.20.1)
                         OPTION=$(whiptail --title "选择功能 ${server_number}_${server_v}" --menu "请选择操作" 20 50 6 \
                         "1" "间歇泉" \
                         "0" "返回上级" 3>&1 1>&2 2>&3)
                                 case ${OPTION} in
                                 1)
                                       if [ ! -d ${HOME}/gancm/server/${server_v}/${server_number}/plugins ]; then
                                       mkdir ${HOME}/gancm/server/${server_v}/${server_number}/plugins
                                       fi
                                       wget https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/spigot -O ${HOME}/gancm/server/${server_v}/${server_number}/plugins/Geyser-Spigot.jar &
                                       jdt 下载适用于Paper的-间歇泉（国外网站下载速度慢）
                                 ;;
                                 esac

                    ;;
                    *)
                         OPTION=$(whiptail --title "选择功能" --menu "请选择操作" 20 50 6 \
                         "0" "返回上级" 3>&1 1>&2 2>&3)
                    ;;
                    esac
               ;;
     esac
        hcjx
}
#以上为函数

if [ ! -f "$(command -v whiptail)" ]; then
    echo -e "$(gettime)${RED}目前并没有安装 whiptail 正在安装${RES}"
    installapt whiptail
fi

if [ ! -f "$(command -v wget)" ];then
    echo -e "$(gettime)${RED}目前并没有安装 wget 正在安装${RES}"
    installapt wget
fi

if [ ! -f "$(command -v jq)" ];then
    echo -e "$(gettime)${RED}目前并没有安装 jq 正在安装${RES}"
    installapt jq
fi
if [ ! -f "$(command -v curl)" ];then
    echo -e "$(gettime)${RED}目前并没有安装 curl 正在安装${RES}"
    installapt curl
fi
if [ ! -f "$(command -v curl)" ];then
    echo -e "$(gettime)${RED}目前并没有安装 bc 正在安装${RES}"
    installapt bc
fi
if [ $(echo $PATH) = "/data/data/com.termux/files/usr/bin" ];then
    systen=termux
elif [ $(echo $PATH) = "/usr/bin" ]; then
    systen=linux
fi

#以上为判断
if [ ! -d ${HOME}/gancm ]; then
    mkdir ${HOME}/gancm
fi
if [ ! -d ${HOME}/gancm/server ]; then
    mkdir ${HOME}/gancm/server
fi
if [ ! -d ${HOME}/gancm/log ]; then
    mkdir ${HOME}/gancm/log
fi
#配置文件检查


case $1 in
    download|Download|dow)
        case $2 in
            spigot|spig)
            download_spigot
            ;;
            paper)
            download_paper
            ;;
        *)
            download
            ;;
        esac
    ;;
    start)
        laststart
    ;;
    help|-help|h|-h)
    echo -e "
    download 别名:Download  dow
      L 参数:spigot 别名:spig 作用:下载spigot服务端
      L 参数:paper 作用: 下载paper服务端
    start
      L 作用:打开服务器管理面板
    help 别名:-help  -h h
      L 打开本帮助页面
    * 无参数或非合法参数打开不合法参数的上级
    "
    ;;
    *)
        if [ systen = termux ];then
         pkg update
          else 
              apt update
          fi
          while true; do
        OPTION=$(whiptail --title "选择功能" --menu "请选择操作" 20 50 6 \
        "1" "管理服务器 " \
        "2" "下载服务器核心" \
        "0" "退出脚本" 3>&1 1>&2 2>&3)
        case $OPTION in
        1)  
            laststart
            ;;
        2)
            download
            ;;  
        0)
             break
             ;;
        *)
             break
             ;;
        esac 
        done
esac    

    
